package cn.xuqiudong.sso.server.controller;

import cn.xuqiudong.common.base.model.BaseResponse;
import cn.xuqiudong.sso.common.constant.Oauth2Constant;
import cn.xuqiudong.sso.common.constant.SsoConstant;
import cn.xuqiudong.sso.common.model.SsoUser;
import cn.xuqiudong.sso.server.service.AppService;
import cn.xuqiudong.sso.server.service.IndexService;
import cn.xuqiudong.sso.server.service.SsoUserService;
import cn.xuqiudong.sso.server.session.SessionManager;
import cn.xuqiudong.sso.server.storage.model.LocalDataCache;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

/**
 * 描述:
 *  登录相关的接口
 *
 * @author Vic.xu
 * @since 2021-10-29 11:08
 */
@Controller
public class IndexController extends BaseSsoController {

    @Resource
    private AppService appService;

    @Resource
    private SsoUserService userService;

    @Resource
    private SessionManager sessionManager;

    @Resource
    private IndexService indexService;

    /**
     * 退出登录
     */
    @GetMapping("logout")
    public String logout(@RequestParam(value = SsoConstant.REDIRECT_URI, required = true) String redirectUri) {
        sessionManager.invalidate(servletRequest, servletResponse);
        return "redirect:" + redirectUri;
    }


    /**
     * 前往登录页面
     */
    @GetMapping("/login")
    public String login(@RequestParam(value = SsoConstant.REDIRECT_URI, required = true) String redirectUri,
                        @RequestParam(value = Oauth2Constant.APP_ID, required = true) String appId, Model model) throws UnsupportedEncodingException {
        String tgt = sessionManager.getTgt(servletRequest);
        //若cookie中不存在票据 则前往登录页面
        if (StringUtils.isEmpty(tgt)) {
            return goLoginPath(redirectUri, appId, model, null);
        }
        //给客户端发授权码并重定向会客户端
        return indexService.generateCodeAndRedirect(redirectUri, tgt);
    }


    /**
     * 登录操作
     *
     * @param redirectUri 重定向回原系统的uri
     * @param appId       唯一标识
     * @param rememberMe  记住我  暂时不处理
     * @param username    用户名
     * @param password    密码
     */
    @PostMapping("/login")
    public String login(@RequestParam(value = SsoConstant.REDIRECT_URI, required = true) String redirectUri,
                        @RequestParam(value = Oauth2Constant.APP_ID, required = true) String appId,
                        @RequestParam(value = Oauth2Constant.GROUP, defaultValue = "") String group,
                        @RequestParam(required = false) boolean rememberMe,
                        @RequestParam String username,
                        @RequestParam String password, Model model) throws UnsupportedEncodingException {

        //检测appid的合法性，不合法则跳回login页面
        if (!appService.checkAppId(appId)) {
            return goLoginPath(redirectUri, appId, model, "非法的应用");
        }

        //登录失败 则返回登录页面重新登录
        BaseResponse<SsoUser> result = userService.login(group, username, password);
        if (!result.isSuccess()) {
            return goLoginPath(redirectUri, appId, model, result.getMsg());
        }
        //登录成功 则创建tgt
        String tgt = sessionManager.createTgt(result.getData(), servletRequest, servletResponse);
        return indexService.generateCodeAndRedirect(redirectUri, tgt);


    }



    /* ************************************************************************** */

    /**
     * 根目录， 用于测试
     *
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping(value = {"", "/"})
    public String home() throws UnsupportedEncodingException {

        String params = "?" + SsoConstant.REDIRECT_URI + "=" + servletRequest.getScheme() + "://" +
                servletRequest.getServerName() + ":" +
                servletRequest.getServerPort() + "/index";
        params = params + "&" + Oauth2Constant.APP_ID + "=" + "testAppId";
        return "redirect:/login" + params;
    }

    /**
     * index 页面 用于测试
     *
     * @param code
     * @param model
     * @return
     */
    @GetMapping("/index")
    public String index(String code, Model model) {
        model.addAttribute("code", code);

        LocalDataCache.printCache();

        return "index";
    }

}
